package com.boot.unity.api.utils;

import cn.hutool.json.JSONException;
import com.boot.unity.api.constants.NotifyType;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "tencent.sms")
@Data
public class ConstantSmsUtils implements InitializingBean {

    private Integer secretId;
    private String secretKey;
    private String signName;
    private List<Map<String, String>> template;

    public static Integer SECRET_ID;
    public static String SECRET_KEY;
    public static String SIGN_NAME;
    public static List<Map<String, String>> TEMPLATES;

    @Override
    public void afterPropertiesSet() throws Exception {
        SECRET_ID = secretId;
        SECRET_KEY = secretKey;
        SIGN_NAME = signName;
        TEMPLATES = template;
    }

    private static volatile ConstantSmsUtils instance = null;

    private ConstantSmsUtils() {

    }

    public static ConstantSmsUtils getInstance() {
        if (instance == null){
            synchronized (ConstantSmsUtils.class){
                if (instance == null) {
                    instance = new ConstantSmsUtils();
                }
            }
        }
        return instance;
    }

    public void send(String phoneNumber, NotifyType notifyType, String[] params) {
        try {
            SmsSingleSender ssender = new SmsSingleSender(SECRET_ID, SECRET_KEY);
            SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumber,
                    getTemplateId(notifyType, TEMPLATES), params, SIGN_NAME, "", "");
        } catch (HTTPException e) {
            // HTTP响应码错误
            e.printStackTrace();
        } catch (JSONException e) {
            // json解析错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络IO错误
            e.printStackTrace();
        }
    }

    private Integer getTemplateId(NotifyType notifyType, List<Map<String, String>> values) {
        Iterator var3 = values.iterator();
        Map<String, String> item;
        String notifyTypeStr;
        do {
            if (!var3.hasNext()) {
                return null;
            }
            item = (Map)var3.next();
            notifyTypeStr = notifyType.getType();
        } while(!item.get("name").equals(notifyTypeStr));
        return Integer.parseInt(item.get("templateId"));
    }
}
